;
(function () {
    
    var JVAutoLoadGFont = new Class({
        options: {},
        initialize: function (el, o) {
            if (o) this.setOptions(o);
            this.install(el);
        },
        install: function (el) {
            var This = this;
            this.scroll = el;
            this.elements = this.scroll.child();
            var timeout;
            this.scroll.addEvent('scroll', function (e) {
                clearTimeout(timeout);
                timeout = setTimeout(function () {
                    This.loadFont();
                }, 500);
            });
        },
        loadFont: function () {
            this.options.scrollTop = this.scroll.scrollTop.toInt();
            this.options.offsetTopScroll = this.scroll.offset().top;

            var index = this.findTopIndex(0, this.elements.length - 1);
            var queued = [];
            for (var i = index; i < this.elements.length; i++) {
                var bottom = this.elements[i].offset().bottom;
                queued.push(this.elements[i].find('label')[0].getText().replace(/\n/g, ''));
                if (bottom > (this.options.scrollTop + this.options.offsetTopScroll + this.scroll.offset().height)) break;
            }
            J.GoogleFont.clearQueued();
            J.GoogleFont.load(queued);
        },
        findTopIndex: function (min, max) {
            var center = Number.toInt((max + min) / 2);
            if (center == max || center == min) return min;
            if (this.elements[center].offset().top < this.options.scrollTop + this.options.offsetTopScroll) {
                return this.findTopIndex(center, max);
            } else {
                return this.findTopIndex(min, center);
            }
        }

    }).extend(new Options);

    //---------------------------------------------------------------------------------------------------------
    var DragFont = new Class({
        options: {
            delay: 200,
            moveType: 'copy',
            //drop
            to: []
        },
        initialize: function (el, o) {
            var This = this;
            if (o) this.setOptions(o);
            if (!this.options.handle) this.options.handle = el;
            var addTo = null;
            var handleEvt = {
                toMoveEnter: function (e) {
                    this.addClass('Jhover');
                    addTo = this;
                },
                toMoveLeave: function (e) {
                    this.removeClass('Jhover');
                    addTo = null;
                }
            }
            this.elementMove = el;
            new J.Drag(this.options.handle, {
                delay: This.options.delay,
                start: function (e) {
                    This.options.to.each(function (to) {
                        to.addEvent('mouseenter', handleEvt.toMoveEnter);
                        to.addEvent('mouseleave', handleEvt.toMoveLeave);
                    });
                    if (This.options.moveType == 'copy') {
                        This.elementMove = el.clone()
                        $$('body')[0].append(This.elementMove);
                        This.elementMove.css({
                            'position': 'absolute',
                            top: e.pageY + 1,
                            left: e.pageX + 1
                        });
                    }
                    return true;
                },
                drag: function (e) {
                    This.elementMove.css({
                        top: e.pageY + 1,
                        left: e.pageX + 1
                    });
                },
                end: function (e) {
                    This.options.to.each(function (to) {
                        to.removeEvent('mouseenter', handleEvt.toMoveEnter);
                        to.removeEvent('mouseenter', handleEvt.toMoveLeave);
                    });
                    if (addTo) {
                        addTo.css('font-family', This.elementMove.child()[0].css('font-family'));
                        addTo.find('.selected_font')[0].setText(This.elementMove.getText());
                        addTo.addClass('selected');
                        addTo.find('.fontval')[0].value = This.elementMove.getText();
                    }
                    This.elementMove.remove();
                }
            });
        }
    }).extend(new Options).extend(new Events);


    //---------------------------------------------------------------------------------------------------------
    window.addEvent('domready', function () {
        //J.GoogleFont.setOptions({});
        var movefontto = $$('.choose-font')[0].child();

        $$('ul.fontlist').each(function (fontList) {
            fontList.AutoLoadFont = new JVAutoLoadGFont(fontList);
            fontList.child().each(function (li) {
                new DragFont(li.child()[0], {
                    to: movefontto
                });
            });
        });

        var fontList = $('font_list');
        var fontApply = $('font_apply');
        J.GoogleFont.addEvent('fontloading', function (fontName) {
            fontName = fontName.trim();
            fontName = fontName.replace(/ /g, '-');
            fontName = fontName.replace(/\n/g, '');
            fontList.find("." + fontName).each(function (status) {
                status.removeClass('inact').removeClass('erro').removeClass('act').addClass('loading');
            });
        });

        J.GoogleFont.addEvent('fontsuccess', function (fontName) {
            fontName = fontName.trim();
            fontName = fontName.replace(/ /g, '-');
            fontName = fontName.replace(/\n/g, '');
            fontList.find("." + fontName).each(function (status) {
                status.removeClass('loading').addClass('act');
            });
        });

        J.GoogleFont.addEvent('fontfailed', function (fontName) {
            fontName = fontName.trim();
            fontName = fontName.replace(/ /g, '-');
            fontName = fontName.replace(/\n/g, '');
            fontList.find("." + fontName).each(function (status) {
                status.removeClass('loading').addClass('error');
            });
        });

        fontList.find('.icon-refresh').each(function (rs) {
            rs.addEvent('click', function () {
                var fontName = this.parent().getText().replace(/\n/g, '');
                J.GoogleFont.reset(fontName);
                J.GoogleFont.load(fontName);
            });
        });

        var createNewGroupFont = function (t, fs) {
                var fonts = new Element('textarea').attr('name', 'params[gfont][' + t + ']').setText(fs);
                fontList.append(fonts);
            }

        var createNewApplyFont = function (t, s) {
                var title = new Element('input').attr({
                    'type': 'hidden',
                    'name': 'params[gfontapply][' + t + '][title]',
                    'value': t
                });
                var font = new Element('input').attr({
                    'type': 'hidden',
                    'name': 'params[gfontapply][' + t + '][font]'
                });
                var selector = new Element('textarea').attr({
                    'class': 'hidden',
                    'name': 'params[gfontapply][' + t + '][selector]',
                    'value': s
                });

                fontApply.append(font).append(selector).append(title);
            }



        fontList.child()[2].addEvent('click', function () {
            var inputTitle = new Element('button', {
                'class': 'btnOk'
            }).setText('Ok');
            var dl = new Element('div', {
                'class': 'dialog'
            }).append(
            new Element('fieldset', {
                'class': 'paramsform'
            }).append(
            new Element('legend').html('Add Font List')).append(
            new Element('table', {

            }).append(
            new Element('tr').append(
            new Element('td').html('Title')).append(
            new Element('td').append(
            new Element('input', {
                'class': 'txttitle'
            })))).append(
            new Element('tr').append(
            new Element('td').html('Fonts')).append(
            new Element('td').append(
            new Element('textarea', {
                'class': 'txtfonts',
                'rows': '8',
                'cols': '45'
            }))))).append(
            inputTitle));

            SqueezeBox.fromElement(dl, {
                handler: 'adopt',
                size: {
                    x: 400,
                    y: 240
                },
                onOpen: function () {
                    var dialog = $$('.dialog')[0];
                    
                    dialog.find('.btnOk')[0].addEvent('click', function () {
                        var txtTitle = dialog.find('.txttitle')[0];
                        var txtFonts = dialog.find('.txtfonts')[0];

                        createNewGroupFont(txtTitle.value, txtFonts.value);
                        submitbutton('apply');
                    });
                }
            });

        });



        fontApply.child()[2].addEvent('click', function () {
            var inputTitle = new Element('input');
            var dl = new Element('div', {
                'class': 'dialog'
            }).append(
            new Element('fieldset', {
                'class': 'paramsform'
            }).append(
            new Element('legend').html('Add Font Apply')).append(
            new Element('table', {

            }).append(
            new Element('tr').append(
            new Element('td').html('Title')).append(
            new Element('td').append(
            new Element('input', {
                'class': 'txttitle'
            })))).append(
            new Element('tr').append(
            new Element('td').html('Selector')).append(
            new Element('td').append(
            new Element('textarea', {
                'class': 'txtSelector',
                'rows': '8',
                'cols': '45'
            }))))).append(
            new Element('input').attr({
                'type': 'button',
                'value': 'Ok',
                'class': 'btnOk'
            })));

            SqueezeBox.fromElement(dl, {
                handler: 'adopt',
                size: {
                    x: 400,
                    y: 240
                },
                onOpen: function () {
                    var dialog = $$('.dialog')[0];
                   
                    dialog.find('.btnOk')[0].addEvent('click', function () {
                        var txtTitle = dialog.find('.txttitle')[0];
                        var txtFont = dialog.find('.txtSelector')[0];

                        createNewApplyFont(txtTitle.value, txtFont.value);
                        submitbutton('apply');
                    });
                }
            });

        });

    });


    function editFontList(id) {
        console.log($('' + id));
        $('' + id).toggleClass('hidden');

    }
    window.addEvent('domready', function () {
        new Accordion($$('span.separator'), $$('ul.fontlist'), {
            onActive: function (toggler, i) {
                var ul = toggler.getParent().addClass('active').find('ul')[0];
                ul.scrollTop
            },
            onBackground: function (toggler, i) {
                toggler.getParent().removeClass('active');
            },
            duration: 300,
            opacity: false,
            alwaysHide: true
        });
    });

})();